package method

import (
	"html/template"
	"io"
	"io/ioutil"
	"net/http"
	"os"
)

const UPLOAD_DIR string = "./upload/"

func ViewHandler(w http.ResponseWriter, r *http.Request) {
	imageID := r.FormValue("id")
	if imageID != "" {
		imagePath := UPLOAD_DIR + imageID
		w.Header().Set("Content-Type", "image")
		http.ServeFile(w, r, imagePath)
	}
}

func ListHandler(w http.ResponseWriter, r *http.Request) {
	files, err := ioutil.ReadDir(UPLOAD_DIR)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	params := make(map[string]interface{})
	images := []string{}
	for _, file := range files {
		images = append(images, file.Name())
	}
	params["images"] = images
	if err = RenderHtml(w, "list", params); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
}

func UploadHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method == "GET" {
		io.WriteString(w, `<html><form method="POST" action="upload" enctype="multipart/form-data">`+
			`choose an image to upload:<input name="image" type="file"/>`+
			`<input type="submit" value="upload"/>`+
			`</form></html>`)
	} else if r.Method == "POST" {
		file, handler, err := r.FormFile("image")
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		defer file.Close()

		fname := handler.Filename
		ftmp, err := os.Create(UPLOAD_DIR + fname)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		defer ftmp.Close()

		if _, err := io.Copy(ftmp, file); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		http.Redirect(w, r, "/view?id="+fname, http.StatusFound)
	}
}

func RenderHtml(w http.ResponseWriter, html string, params map[string]interface{}) (err error) {
	t, err := template.ParseFiles("src/template/" + html + ".html")
	if err != nil {
		return
	}
	err = t.Execute(w, params)
	return
}
